﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;

public partial class Basic : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == true)
        {
            DoPostBackAction();
        }
        else
        {
            if (this.PreviousPage!=null)
                if (this.PreviousPage.IsCrossPagePostBack == true)
                {
                    return;
                }
        }

        string msp = Request.Params["MSP"]; // Mã sản phẩm
        if (msp != null)
        {
            ShowName(msp);
            ShowLargePic(msp);
            ShowPictures(msp);
            ShowDetail(msp);
            ShowComment(msp);
            ShowSameKind(msp);
            ShowDetailBid(msp);
            lbMSP.Text = msp;
        }        
    }

    
    protected void Page_PreRender(object sender, EventArgs e)
    {
        InitPageLoad(); // Hàm này được gọi khi bắt đầu dàn trang, sau khi đã đọc dữ liệu từ server, sau basic.master.Page_Load
    }

    private void InitPageLoad()
    {
    }

    private void DoPostBackAction()
    {
        string actionCode = Request.Form.Get("__EVENTTARGET");  // or string actionCode = Request.Params.Get("__EVENTTARGET");
        switch (actionCode)
        {
            case "datgia": DatGia();
                break;
        }
    }

    private void DatGia()
    {
        
        if (CheckForLogin())
        {
            try
            {
                string userID = GetIDUserLogin();
                string msp = lbMSP.Text;
                int curValue = GiaHienTai(msp);

                int value = int.Parse(txtDatGia.Text);
                if (value > curValue)
                    DatGiaSuccess(msp, value.ToString());
                else
                    lbError.Text = "Giá phải lớn hơn giá hiện tại.";
            }
            catch(Exception ex)
            {
                lbError.Text = "Nhập sai định dạng số.";
                lbError.Visible = true;
            }
        }
        else
            lbError.Text = "Bạn phải đăng nhập!";

        txtDatGia.Text = "";
        lbError.Visible = true;
    }


    private void DatGiaSuccess(string msp, string value)
    {
        lbError.Text = "Đặt giá thất bại.";
        
        string userid = GetIDUserLogin();
        string now = DateTime.Now.ToString("s");
        string qInsert = "insert into CHITIETDAUGIA(MaTaiKhoan,GiaGiaoDich,ThoiGianGiaoDich,TinhTrang,MaSanPham) values ('" +userid+ "','" +value+ "','" +now+ "','dat','" +msp+ "')";
        SqlCommand cmd = new SqlCommand(qInsert, Helper.ConnectToDataBase());
        int re = cmd.ExecuteNonQuery();
        if (re != -1)
            if(ModifyGiaHienTai(msp, value))
                lbError.Text = "Đặt giá thành công.";
        
        lbError.Visible = true;
    }
    private bool ModifyGiaHienTai(string msp, string value)
    {
        string qUpdate = "update SANPHAM set GiaHienTai='" +value+ "' where MaSanPham="+msp;
        SqlCommand cmd = new SqlCommand(qUpdate, Helper.ConnectToDataBase());
        if (cmd.ExecuteNonQuery() != -1)
            return true;
        return false;
    }

    private int GiaHienTai(string msp)
    {
        string qSelect = "select GiaHienTai from SANPHAM where MaSanPham=" + msp;
        SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
        SqlDataReader rd = cmd.ExecuteReader();
        if (rd != null)
        {
            rd.Read();
            return int.Parse(rd.GetString(0));
        }
        return -1;
    }

    private void ShowDetail(string msp)
    {
        //string qSelect = "Select a.MaSanPham, a.MaTaiKhoan, TenSanPham,GiaKhoiDiem,GiaHienTai,NgayDang,NgayHetHan,HinhAnh,MoTaSanPham,TenTaiKhoan,DiemTinCayBan, count(b.MaChiTietDauGia) as SoLuotDauGia from SANPHAM a, CHITIETDAUGIA b, TAIKHOAN c where a.MaSanPham="+msp+" and b.MaSanPham = a.MaSanPham and a.MaTaiKhoan=c.MaTaiKhoan group by a.MaSanPham, a.MaTaiKhoan, TenSanPham,GiaKhoiDiem,GiaHienTai,NgayDang,NgayHetHan,HinhAnh,MoTaSanPham,TenTaiKhoan,DiemTinCayBan ";
        string qSelect = "Select a.MaSanPham, a.MaTaiKhoan, TenSanPham,GiaKhoiDiem,GiaHienTai,NgayDang,NgayHetHan,HinhAnh,MoTaSanPham,TenTaiKhoan,DiemTinCayBan, count(b.MaChiTietDauGia) as SoLuotDauGia from TAIKHOAN c , SANPHAM a left join CHITIETDAUGIA b on b.MaSanPham = a.MaSanPham where a.MaTaiKhoan=c.MaTaiKhoan and  a.MaSanPham="+msp+" group by a.MaSanPham, a.MaTaiKhoan, TenSanPham,GiaKhoiDiem,GiaHienTai,NgayDang,NgayHetHan,HinhAnh,MoTaSanPham,TenTaiKhoan,DiemTinCayBan";
        SqlCommand cmd = new SqlCommand(qSelect,Helper.ConnectToDataBase());
        DataListDetail.DataSource = cmd.ExecuteReader();
        DataListDetail.DataBind();
    }


    private void ShowPictures(string msp)
    {
        string qSelect = "select a.MaTaiKhoan, a.HinhAnh ,c.TenMT from SANPHAM a,SANPHAM_MULTIMEDIA b, MULTIMEDIA c where a.MaSanPham=" + msp + " and b.MaSanPham=" + msp + " and c.MaMT=b.MaMT";
        SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
        rptPictures.DataSource = cmd.ExecuteReader();
        rptPictures.DataBind();

    }
    private void ShowComment(string msp)
    {
        string qSelect = "select a.MaTaiKhoan, TenTaiKhoan,NgayComment,NoiDungComment from TAIKHOAN a, COMMENT b where b.MaSanPham = "+msp+" and a.MaTaiKhoan = b.MaTaiKhoan";
        SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
        DataListComment.DataSource = cmd.ExecuteReader();
        DataListComment.DataBind();
    }

    private void ShowSameKind(string msp)
    {
        string qSelect = "select b.MaTaiKhoan, b.MaSanPham, b.TenSanPham, b.HinhAnh from SanPham a, SanPham b where a.MaLoaiSanPham=b.MaLoaiSanPham and a.MaSanPham="+msp+" and b.MaSanPham!="+msp;
        SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
        DataListSameKind.DataSource = cmd.ExecuteReader();
        DataListSameKind.DataBind();
    }

    private void ShowDetailBid(string msp)
    {
        string qSelect = "select TenTaiKhoan, GiaGiaoDich from CHITIETDAUGIA a, TAIKHOAN b where MaSanPham=" +msp+ " and b.MaTaiKhoan=a.MaTaiKhoan";
        SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
        rptChiTietDatGia.DataSource = cmd.ExecuteReader();
        rptChiTietDatGia.DataBind();
    }

    private void ShowLargePic(string msp)
    {
        string qSelect = "select MaTaiKhoan, HinhAnh from SANPHAM where MaSanPham=" + msp;
        SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
        rptLargePic.DataSource = cmd.ExecuteReader();
        rptLargePic.DataBind();
    }

    private void ShowName(string msp)
    {
        string qSelect = "select TenSanPham from SANPHAM where MaSanPham=" + msp;
        SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
        rptName.DataSource = cmd.ExecuteReader();
        rptName.DataBind();
    }

    protected void btComment_Click(object sender, EventArgs e)
    {
        if (CheckForLogin() == false)
        {
            lbError.Text = "Bạn phải đăng nhập";
            return;
        }


        string userid = GetIDUserLogin();
        string comment = txtComment.Text.Trim();
        string productID = lbMSP.Text;
        if (comment.Length == 0 || productID.Length==0)
            return;

        string nowTime = DateTime.Now.ToString("s");
        string query = "insert into COMMENT ([NoiDungComment],[NgayComment],[MaTaiKhoan],[MaSanPham]) values (N'" 
                        + comment + "','" + nowTime + "'," + userid + "," + productID + ")";

        SqlCommand cmd = new SqlCommand(query,Helper.ConnectToDataBase());
        int re = cmd.ExecuteNonQuery();
        Helper.DisposeCommand(ref cmd);

        if (re == -1)
        {
            ShowError("Lỗi 100. Không thể đăng bình luận.");
            return;
        }

        Page.Response.Redirect(HttpContext.Current.Request.Url.ToString(), true); //auto refresh page
    }

    private void ShowError(string errorMessage)
    {
        TextBox txtEr = new TextBox();
        txtEr.Text = errorMessage;
        txtEr.Visible = true;
    }

    private bool CheckForLogin()
    {
        string maTaiKhoan = GetIDUserLogin();
        if (maTaiKhoan.Length > 0)
            return true;
        return false;
    }

    private string GetIDUserLogin()
    {
        string userid = "";
        if (Request.Cookies["daugia_user"] != null)
            userid = Request.Cookies["daugia_user"]["userid"];
        return userid;
    }


}
